package com.hsd.whb.service.impl;

import com.hsd.whb.entity.Manager;
import com.hsd.whb.enums.ResultEnum;
import com.hsd.whb.exception.HwbException;
import com.hsd.whb.repository.ManagerRepository;
import com.hsd.whb.service.ManagerService;
import com.wangjiacai.hqlQuery.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;


@Service
public class ManagerServiceImpl extends BaseServiceImpl implements ManagerService {

    @Autowired
    private ManagerRepository managerRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public Manager register(Manager manager) {
        validAddManager(manager);
        manager.setLogincount(0);
        manager.setDeleted(0);
        manager.setPassword(passwordEncoder.encode(manager.getPassword()));
        return managerRepository.save(manager);
    }

    private void validAddManager(Manager manager) {
        if (managerRepository.findByUsername(manager.getUsername()) != null) {
            throw new HwbException(ResultEnum.USERNAME_EXITS);
        }
        if (managerRepository.findByEnterpriseAddress(manager.getEnterpriseAddress()) != null) {
            throw new HwbException(ResultEnum.MANAGER_ENTERPRISE_ADDRESS_EXITS);
        }
        if (managerRepository.findByEnterpriseCode(manager.getEnterpriseCode()) != null) {
            throw new HwbException(ResultEnum.MANAGER_ENTERPRISE_CODE_EXITS);
        }
    }

    @Override
    public Manager findByUsername(String username) {
        return managerRepository.findByUsername(username);
    }

    @Override
    public Manager update(Manager manager) {
        validUpdateManager(manager);
        return managerRepository.save(manager);
    }

    private void validUpdateManager(Manager manager) {
        Manager manager1 = managerRepository.getOne(manager.getId());
        if (!manager.getPhone().equals(manager1.getPhone())) {
            if (managerRepository.findByPhone(manager.getPhone()) != null) {
                throw new HwbException(ResultEnum.PHONE_EXITS);
            }
        }
        if (!manager.getEmail().equals(manager1.getEmail())) {
            if (managerRepository.findByEmail(manager.getEmail()) != null) {
                throw new HwbException(ResultEnum.EMAIL_EXITS);
            }
        }
    }


    @Override
    public Manager findById(Integer id) {
        return managerRepository.getOne(id);
    }
}
